import {
  CopyDocument,
  Delete,
  DocumentCopy,
  Open,
  Edit,
  List,
  Refresh,
  Camera,
  SwitchButton
} from '@element-plus/icons-vue';
import eventBus from 'vue3-eventbus';
import { deepCopy } from 'windicss/utils';
import {ElMessage, ElMessageBox} from 'element-plus';
import {emitter} from "@/utils/bus";
import {categoryMap} from "./config";

let pathFlag = null;
export const optionButton = graph => {
  return {
    options: [
      {
        name: '回退(最多回退5次)',
        icon: 'xfv-icon-undo',
        click: arg => {
          const isUndo = graph.canUndo();
          return isUndo ? graph.undo() : false;
        },
      },
      {
        name: '清除画布',
        icon: 'xfv-icon-clear',
        click: arg => {},
      },
      // {
      //   name: '重置',
      //   icon: 'xfv-icon-redo',
      //   click: (arg) => {
      //     const isRedo = graph.canRedo()
      //     return isRedo ? graph.canRedo() : false
      //   },
      // },
      {
        name: '全选',
        icon: 'xfv-icon-select-all',
        click: arg => {},
      },
      {
        name: '放大',
        icon: 'xfv-icon-zoom-in',
        click: arg => {
          graph.zoom(0.2);
        },
      },
      {
        name: '缩小',
        icon: 'xfv-icon-zoom-out',
        click: arg => {
          graph.zoom(-0.2);
        },
      },
      {
        name: '实际大小',
        icon: 'xfv-icon-actual-size',
        click: arg => {
          graph.zoomToFit({ maxScale: 1 });
        },
      },
      {
        name: '复制',
        icon: 'xfv-icon-copy',
        click: arg => {
          const cells = graph.getSelectedCells();
          return cells.length ? graph.copy(cells) : false;
        },
      },
      {
        name: '粘贴',
        icon: 'xfv-icon-paste',
        click: arg => {
          const clipBoard = graph.isClipboardEmpty();
          if (!clipBoard) {
            graph.paste({ offset: { dx: 50, dy: 32 } });
            return graph.cleanSelection();
          }
          return false;
        },
      },
    ],
    download: [
      {
        id: 'preview',
        name: '预览',
        icon: 'xfv-icon-preview',
        type: 'click',
        click: () => {},
      },
      {
        id: 'downloadType',
        name: '下载',
        icon: 'xfv-icon-download',
        type: 'select',
        selectChildren: [
          {
            id: 'image',
            name: '图片',
            icon: 'xfv-icon-image',
            click: () => {},
          },
          {
            id: 'json',
            name: 'Json',
            icon: 'xfv-icon-json',
            click: () => {},
          },
        ],
      },
    ],
    select: [
      {
        id: 'lineType',
        name: '连线类型',
        icon: 'xfv-icon-flow-line',
        type: 'select',
        value: '',
        selectChildren: [
          {
            id: 'line',
            name: '直角直线',
            icon: 'xfv-icon-flow-line',
          },
          {
            id: 'broken',
            name: '直角曲线',
            icon: 'xfv-icon-flow-broken',
          },
          {
            id: 'curve',
            name: '平滑曲线',
            icon: 'xfv-icon-flow-curve',
          },
        ],
      },
      {
        id: 'lineStyle',
        name: '连线样式',
        icon: 'xfv-icon-solid',
        type: 'select',
        selectChildren: [
          {
            id: 'dashed',
            name: '实线',
            icon: 'xfv-icon-solid',
          },
          {
            id: 'dashed',
            name: '实线',
            icon: 'xfv-icon-dashed',
          },
        ],
      },
      {
        name: '连线宽度',
        icon: 'xfv-icon-line-width',
        type: 'select',
        value: '',
        selectChildren: [
          { id: '1px', name: '1px' },
          { id: '2px', name: '2px' },
          { id: '3px', name: '3px' },
          { id: '4px', name: '4px' },
          { id: '5px', name: '5px' },
        ],
      },
      // , {
      //   name: '连线颜色',
      //   icon: 'xfv-icon-edit',
      // },
      // {
      //   name: '起点',
      //   icon: Back,
      // },
      // {
      //   name: '终点',
      //   icon: Right,
      // },
    ],
  };
};

/**
 * 删除节点
 * @param isGernerate
 * @param cell
 */
const deleteNode = (isGernerate, cell) =>{
  if (isGernerate(cell)) {
    ElMessageBox.confirm(`确认是否删除!`, {
      confirmButtonText: '删 除',
      cancelButtonText: '取 消',
      type: 'warning',
      center: true,
      customClass: 'delMessageBox',
      confirmButtonClass: 'delButtonClass',
    }).then(async () => {
      eventBus.emit('removeScreenNode', {
        type: 'node',
        value: cell,
      });
    });
  } else {
    eventBus.emit('removeScreenNode', {
      type: 'node',
      value: cell,
    });
  }
}

// export const nodeMenuButton = ({ graph, cell }, cb) => {
//
//   // 通过颜色判断是否生成
//   const isGernerate = item => {
//
//     if(item.attrs['.rank']) {
//       return (
//           item.attrs['.rank'].fill === '#67C23A' ||
//           item.attrs['.rank'].fill === '#F56C6C'
//       );
//     } else {
//       return false;
//     }
//   };
//
//   const category =
//     cell.attrs.image &&
//     cell.attrs.image.options &&
//     cell.attrs.image.options.category
//       ? cell.attrs.image.options.category
//       : 5;
//
//   let flag =
//     cell.attrs['.rank'] && cell.attrs['.rank'].fill == '#67C23A'
//       ? '关闭'
//       : '开启';
//   let arr = [
//     {
//       name: flag,
//       type: 'copy',
//       icon: Open,
//       color: '#909399',
//       click: () => {
//         eventBus.emit('openFunc', { flag: flag === '开启' ? 'start' : 'stop', cell: cell });
//         cb(false);
//       },
//     },
//     {
//       name: '编辑',
//       icon: Edit,
//       type: 'edit',
//       color: '#409EFF',
//       click: arg => {
//         eventBus.emit('editNode', cell);
//         cb(false);
//       },
//     },
//     {
//       name: '复制',
//       type: 'copy',
//       icon: CopyDocument,
//       color: '#909399',
//       click: () => {
//         graph.copy([cell]);
//         cb(false);
//       },
//     },
//     {
//       name: '删除',
//       icon: Delete,
//       color: '#F56C6C',
//       click: arg => {
//
//         pathFlag = window.location.href.indexOf('/scenes/manage');
//
//
//         if (pathFlag === -1) {
//           graph.removeCell(cell);
//         } else {
//           let cells = graph.getSelectedCells();
//           if (cells.length) {
//             let flag = false, isEmpty = false;
//
//             // 判断当前节点是否在选中节点之内
//             for (let i = 0; i < cells.length; i++) {
//               if(cell.id === cells[i].id) {
//                 isEmpty = true;
//                 break;
//               }
//             }
//
//             if(isEmpty) {
//               for (let i = 0; i < cells.length; i++) {
//                 flag = isGernerate(cells[i]);
//                 break;
//               }
//
//               if (flag) {
//                 ElMessageBox.confirm(`确认是否删除!`, {
//                   confirmButtonText: '删 除',
//                   cancelButtonText: '取 消',
//                   type: 'warning',
//                   center: true,
//                   customClass: 'delMessageBox',
//                   confirmButtonClass: 'delButtonClass',
//                 }).then(async () => {
//                   cells.forEach(item => {
//                     eventBus.emit('removeScreenNode', {
//                       type: 'node',
//                       value: item,
//                     });
//                   });
//                 });
//               } else {
//                 cells.forEach(item => {
//                   eventBus.emit('removeScreenNode', {
//                     type: 'node',
//                     value: item,
//                   });
//                 });
//               }
//             } else {
//               deleteNode(isGernerate, cell);
//             }
//           } else {
//             deleteNode(isGernerate, cell);
//           }
//         }
//         cb(false);
//       },
//     },
//   ];
//
//   // 虚拟机、容器未生成去掉开启
//   if((category === 1 || category === 2)  && !isGernerate(cell) ) {
//     arr.splice(0, 1);
//   }
//
//   // 重启跟关闭绑定
//   if((category === 1 || category === 2)  && flag === '关闭') {
//     arr.splice(1, 0 , {
//       name: '重启',
//       type: 'copy',
//       icon: SwitchButton,
//       color: '#409EFF',
//       click: () => {
//         eventBus.emit('openFunc', { flag: 'restart', cell: cell });
//         cb(false);
//       },
//     });
//   }
//
//   // 重置（已生成的虚拟机、容器）
//   if((category === 1 || category === 2)  && isGernerate(cell) ) {
//     arr.splice(2, 0 , {
//       name: '重置',
//       type: 'reset',
//       icon: 'Refresh',
//       color: '#409EFF',
//       click: () => {
//         ElMessageBox.confirm(
//             `重置${category === 1 ? '虚拟机' : '容器'} ,重置后将不可恢复!`,
//             '重置',
//             {
//               confirmButtonText: '确 定',
//               cancelButtonText: '取 消',
//               type: 'warning',
//               center: true
//             },
//         ).then(async () => {
//           eventBus.emit('openFunc', { flag: 'reset', cell: cell });
//         });
//         cb(false);
//       },
//     });
//   }
//
//   if (category === 1 && isGernerate(cell) ) {
//     let arr1 = deepCopy(arr);
//     arr1.splice(2, 0, {
//       name: '快照',
//       icon: Camera,
//       type: 'edit',
//       color: '#409EFF',
//       click: arg => {
//         emitter.emit('snapshotDialog', cell);
//         cb(false);
//       },
//     });
//     return arr1;
//   } else if (category === 2) {
//     let arr1 = deepCopy(arr);
//     arr1.push({
//       name: '日志',
//       icon: List,
//       type: 'edit',
//       color: '#e6a23c',
//       click: arg => {
//         eventBus.emit('containerLogs', cell);
//         cb(false);
//       },
//     });
//     return arr1;
//   } else if (category === 4) {
//     let arr1 = deepCopy(arr);
//     // 集群网络
//     arr1.push({
//       name: '流量重放',
//       icon: Refresh,
//       type: 'edit',
//       color: '#409EFF',
//       click: arg => {
//         eventBus.emit('trafficReplay', cell);
//         cb(false);
//       },
//     });
//     return arr1.slice(2, arr1.length);
//   } else if (category === 6) {
//     let arr1 = deepCopy(arr);
//     // 游离网桥
//     arr1.push({
//       name: '流量重放',
//       icon: Refresh,
//       type: 'edit',
//       color: '#409EFF',
//       click: arg => {
//         eventBus.emit('trafficReplay', cell);
//         cb(false);
//       },
//     });
//     return arr1.slice(1, arr1.length);
//   } else if (category === 7 || category === 8) {
//     // 物理设备
//     let arr1 = deepCopy(arr);
//     return arr1.slice(1, arr1.length);
//   } else if (!category || category === 5) {
//     pathFlag = window.location.href.indexOf('/scenes/manage');
//     // 内置组件
//     let arr1 = deepCopy(arr);
//     if (pathFlag === -1) {
//       let designArr = arr1.slice(2, arr1.length);
//       designArr.push({
//             name: '绑定',
//             icon: 'Paperclip',
//             type: 'edit',
//             color: '#409EFF',
//             click: arg => {
//               eventBus.emit('bindComponent', cell);
//               cb(false);
//             },
//           }, {
//         name: '连接',
//         icon: 'SemiSelect',
//         type: 'edit',
//         color: '#409EFF',
//         click: arg => {
//           eventBus.emit('linkComponentDesign', cell);
//           cb(false);
//         },
//       })
//       return designArr;
//     } else {
//       return arr1.slice(2, arr1.length);
//     }
//   } else if (category === 9) {
//     let arr1 = deepCopy(arr);
//     arr1.push({
//       name: '工具执行',
//       icon: Refresh,
//       type: 'edit',
//       color: '#409EFF',
//       click: arg => {
//         eventBus.emit('toolExecute', cell);
//         cb(false);
//       },
//     });
//     return arr1;
//   } else {
//     return arr;
//   }
// };

export const edgeMenuButton = ({ graph, cell }, cb) => {
  return [
    {
      type: 'lineType',
      name: '连线类型',
      children: [
        {
          name: '实线',
          click: () => {
            cell &&
              cell.attr({
                line: {
                  strokeDasharray: 0,
                },
              });
            eventBus.emit('changePutGraph', {
              type: 'edge',
              value: cell,
              jsonValue: cell.toJSON(),
              operationType: 'update',
            });
            cb(false);
          },
        },
        {
          name: '虚线',
          click: () => {
            cell &&
              cell.attr({
                line: {
                  strokeDasharray: 6,
                },
              });
            eventBus.emit('changePutGraph', {
              type: 'edge',
              value: cell,
              jsonValue: cell.toJSON(),
              operationType: 'update',
            });
            cb(false);
          },
        },
      ],
    },
    {
      name: '连线样式',
      type: 'lineStyle',
      children: [
        {
          name: '直线',
          click: () => {
            cell && cell.setRouter('normal');
            cell && cell.setConnector('');
            eventBus.emit('changePutGraph', {
              type: 'edge',
              value: cell,
              jsonValue: cell.toJSON(),
              operationType: 'update',
            });
            cb(false);
          },
        },
        {
          name: '折线',
          click: () => {
            cell && cell.setRouter('manhattan');
            cell && cell.setConnector('normal');
            eventBus.emit('changePutGraph', {
              type: 'edge',
              value: cell,
              jsonValue: cell.toJSON(),
              operationType: 'update',
            });
            cb(false);
          },
        },
        {
          name: '曲线',
          click: () => {
            cell && cell.setRouter('orth');
            cell && cell.setConnector('smooth');
            eventBus.emit('changePutGraph', {
              type: 'edge',
              value: cell,
              jsonValue: cell.toJSON(),
              operationType: 'update',
            });
            cb(false);
          },
        },
      ],
    },

    {
      name: '删除',
      type: 'lineDelete',
      icon: Delete,
      color: '#F56C6C',
      click: () => {
        pathFlag = DATA_INFO.currentRoute.name !== 'ScenesManage'
        if (pathFlag) {
          graph.removeCell(cell);
        } else {
          eventBus.emit('removeScreenNode', { type: 'edge', value: cell });
        }
        cb(false);
      },
    },
  ];
};
export const engineEdgeMenuButton = ({ graph, cell }, cb) => {
  return [
    {
      name: '调整路径',
      icon: Edit,
      color: '#342d2d',
      click: () => {
        eventBus.emit('linkPathUpdate', { type: 'edge', value: cell });
        cb(false);
      },
    },
    {
      name: '删除',
      icon: Delete,
      color: '#F56C6C',
      click: () => {
        pathFlag = DATA_INFO.currentRoute.name !== 'ScenesManage'
        if (pathFlag) {
          graph.removeCell(cell);
        } else {
          eventBus.emit('removeScreenNode', { type: 'edge', value: cell });
        }
        cb(false);
      },
    },
  ];
};

export const copyNodeMenuButton = ({ graph, cell }, cb) => {
  let category = cell.attrs.image.options.category;

  let flag =
    cell.attrs['.rank'] && cell.attrs['.rank'].fill == '#67C23A'
      ? '关闭'
      : '开启';
  let arr = [
    {
      name: flag,
      type: 'copy',
      icon: Open,
      color: '#909399',
      click: () => {
        eventBus.emit('openFunc', { flag: flag, cell: cell });
        cb(false);
      },
    },
    {
      name: '编辑',
      icon: Edit,
      type: 'edit',
      color: '#409EFF',
      click: arg => {
        eventBus.emit('editNode', cell);
        cb(false);
      },
    },
  ];
  if (category === 2) {
    // 容器
    let arr1 = deepCopy(arr);
    arr1.push({
      name: '日志',
      icon: List,
      type: 'edit',
      color: '#e6a23c',
      click: arg => {
        eventBus.emit('containerLogs', cell);
        cb(false);
      },
    });
    return arr1;
  } else if (category === 6) {
    // 游离网桥
    let arr1 = deepCopy(arr);
    return arr1.slice(1, arr1.length);
  } else if (category === 9) {
    let arr1 = deepCopy(arr);
    arr1.push({
      name: '工具执行',
      icon: Refresh,
      type: 'edit',
      color: '#409EFF',
      click: arg => {
        eventBus.emit('toolExecute', cell);
        cb(false);
      },
    });
    return arr1;
  } else {
    return arr;
  }
};


// 通过颜色判断是否生成
const isGernerate = item => {

  if(item.attrs['.rank']) {
    return (
        item.attrs['.rank'].fill === '#67C23A' ||
        item.attrs['.rank'].fill === '#F56C6C'
    );
  } else {
    return false;
  }
};

const menuButtonOrder = (graph, cell, cb) => {
  return [
    {
      name: '开启',
      type: 'copy',
      icon: Open,
      color: '#909399',
      click: () => {
        eventBus.emit('openFunc', { flag: 'start', cell: cell });
        cb(false);
      },
    },
    {
      name: '关闭',
      type: 'copy',
      icon: Open,
      color: '#909399',
      click: () => {
        eventBus.emit('openFunc', { flag: 'stop', cell: cell });
        cb(false);
      },
    },
    {
      name: '重启',
      type: 'copy',
      icon: SwitchButton,
      color: '#409EFF',
      click: () => {
        eventBus.emit('openFunc', { flag: 'restart', cell: cell });
        cb(false);
      },
    },
    {
      name: '编辑',
      icon: Edit,
      type: 'edit',
      color: '#409EFF',
      click: arg => {
        eventBus.emit('editNode', cell);
        cb(false);
      },
    },
    {
      name: '快照',
      icon: Camera,
      type: 'edit',
      color: '#409EFF',
      click: arg => {
        emitter.emit('snapshotDialog', cell);
        cb(false);
      },
    },
    {
      name: '重置',
      type: 'reset',
      icon: 'Refresh',
      color: '#409EFF',
      click: () => {
        let category = cell.attrs.image.options?.category;
        ElMessageBox.confirm(
            `重置${category === 1 ? '虚拟机' : '容器'} ,重置后将不可恢复!`,
            '重置',
            {
              confirmButtonText: '确 定',
              cancelButtonText: '取 消',
              type: 'warning',
              center: true
            },
        ).then(async () => {
          eventBus.emit('openFunc', { flag: 'reset', cell: cell });
        });
        cb(false);
      },
    },
    {
      name: '日志',
      icon: List,
      type: 'edit',
      color: '#e6a23c',
      click: arg => {
        eventBus.emit('containerLogs', cell);
        cb(false);
      },
    },
    {
      name: '流量重放',
      icon: Refresh,
      type: 'edit',
      color: '#409EFF',
      click: arg => {
        eventBus.emit('trafficReplay', cell);
        cb(false);
      },
    },
    {
      name: '绑定',
      icon: 'Paperclip',
      type: 'edit',
      color: '#409EFF',
      click: arg => {
        eventBus.emit('bindComponent', cell);
        cb(false);
      },
    },
    {
      name: '连接',
      icon: 'SemiSelect',
      type: 'edit',
      color: '#409EFF',
      click: arg => {
        eventBus.emit('linkComponentDesign', cell);
        cb(false);
      },
    },
    {
      name: '工具执行',
      icon: Refresh,
      type: 'edit',
      color: '#409EFF',
      click: arg => {
        eventBus.emit('toolExecute', cell);
        cb(false);
      },
    },
    {
      name: '复制',
      type: 'copy',
      icon: CopyDocument,
      color: '#909399',
      click: () => {
        graph.copy([cell]);
        cb(false);
      },
    },
    {
      name: '删除',
      icon: Delete,
      color: '#F56C6C',
      click: arg => {
        pathFlag = DATA_INFO.currentRoute.name !== 'ScenesManage'
        if (pathFlag) {
          graph.removeCell(cell);
        } else {
          let cells = graph.getSelectedCells();
          if (cells.length) {
            let flag = false, isEmpty = false;

            // 判断当前节点是否在选中节点之内
            for (let i = 0; i < cells.length; i++) {
              if(cell.id === cells[i].id) {
                isEmpty = true;
                break;
              }
            }

            if(isEmpty) {
              for (let i = 0; i < cells.length; i++) {
                flag = isGernerate(cells[i]);
                break;
              }

              if (flag) {
                ElMessageBox.confirm(`确认是否删除!`, {
                  confirmButtonText: '删 除',
                  cancelButtonText: '取 消',
                  type: 'warning',
                  center: true,
                  customClass: 'delMessageBox',
                  confirmButtonClass: 'delButtonClass',
                }).then(async () => {
                  cells.forEach(item => {
                    eventBus.emit('removeScreenNode', {
                      type: 'node',
                      value: item,
                    });
                  });
                });
              } else {
                cells.forEach(item => {
                  eventBus.emit('removeScreenNode', {
                    type: 'node',
                    value: item,
                  });
                });
              }
            } else {
              deleteNode(isGernerate, cell);
            }
          } else {
            deleteNode(isGernerate, cell);
          }
        }
        cb(false);
      },
    },
  ]
}

export const nodeMenuButton = ({ graph, cell }, cb) => {
  const category =
      cell.attrs.image &&
      cell.attrs.image.options &&
      cell.attrs.image.options.category
          ? cell.attrs.image.options.category
          : 5;

  let currentCategory = null;
  for (let i = 0; i < categoryMap.length; i++) {
    if (category === categoryMap[i].category) {
      currentCategory = categoryMap[i];
      break;
    }
  }

  // 虚拟机映射数组
  let vmWareArr = new Array(13).fill(0)

  // docker映射数组
  let dockerArr = new Array(13).fill(0)

  // 集群网络映射数组
  let clusterArr = [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1];

  // 沙箱网络映射数组
  let sandboxArr = [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1];

  // vpc网络映射数组
  let vpcArr = new Array(13).fill(0)

  // 内置图形映射数组
  let builtInArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1];

  // 物理设备
  let deviceArr = [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1];

  let categoryMapObj = {
    'vmWare': vmWareArr, // 虚拟机映射数组
    'docker': dockerArr, // docker映射数组
    'cluster': clusterArr, // 集群网络映射数组
    'sandbox': sandboxArr, // 沙箱网络映射数组
    'vpc': vpcArr, // vpc网络映射数组
    'builtIn': builtInArr, // 内置图形映射数组
    'localDevice': deviceArr, // 本地实物组件实例（物理设备）映射数组
    'remoteDevice': deviceArr, // 远程实物组件实例（物理设备）映射数组
  }

  let flag =
      cell.attrs['.rank'] && cell.attrs['.rank'].fill === '#67C23A'
          ? '关闭'
          : '开启';
  pathFlag = DATA_INFO.currentRoute.name !== 'ScenesManage'

  // 判断是否是生成节点
  if (!isGernerate(cell)) {
    vmWareArr = Object.assign(vmWareArr, [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1]);
    dockerArr = Object.assign(dockerArr, [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1]);
    vpcArr = Object.assign(vpcArr, [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1]);
  } else {
    vmWareArr = Object.assign(vmWareArr, [1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1]);
    dockerArr = Object.assign(dockerArr, [1, 0, 0, 1,  0, 1, 1, 0, 0, 0, 0, 1, 1]);
    vpcArr = Object.assign(vpcArr, [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1]);
    if (flag === '关闭') {
      vmWareArr = Object.assign(vmWareArr, [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1]);
      dockerArr = Object.assign(dockerArr, [0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1]);
      vpcArr = Object.assign(vpcArr, [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1]);
    }
  }

  if (pathFlag) {
    builtInArr = Object.assign(builtInArr, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1]);
  }

  // 映射
  return menuButtonOrder(graph, cell, cb).filter((item, index) => {
    if ( categoryMapObj[currentCategory.code][index] === 1) {
      return item;
    }
  })
}
